using MediatR;
using WMS.Domain;
using WMS.ErrorCode;
using WMS.Infrasturcture.Interfaces;
using WMS.WebApiRead.Application.Command;

namespace WMS.WebApiRead.Application.Commandhandler
{
    /// <summary>
    /// 处理 <see cref="HandlerInfoQueryCommand"/> 查询命令的处理器
    /// </summary>
    public class HandlerInfoQueryCommandHandler : IRequestHandler<HandlerInfoQueryCommand, ApiResult<List<HandlerInfo>>>
    {
        private readonly IBaseRepository<HandlerInfo> handlerInfoRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="handlerInfoRepository">经办人信息仓储接口</param>
        public HandlerInfoQueryCommandHandler(IBaseRepository<HandlerInfo> handlerInfoRepository)
        {
            this.handlerInfoRepository = handlerInfoRepository;
        }

        /// <summary>
        /// 处理 <see cref="HandlerInfoQueryCommand"/> 命令
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>返回经办人信息列表</returns>
        public async Task<ApiResult<List<HandlerInfo>>> Handle(HandlerInfoQueryCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 获取所有未删除的经办人信息
                var query = handlerInfoRepository.GetAll().Where(x => !x.IsDeleted);

                // 如果提供了仓库部门编号，则按部门编号筛选
                if (request.WarehouseDeptId.HasValue)
                {
                    query = query.Where(x => x.WarehouseDeptId == request.WarehouseDeptId.Value);
                }

                var handlerInfoList = query.ToList();

                return new ApiResult<List<HandlerInfo>>
                {
                    Code = ApiResultEnum.查询成功,
                    Message = "查询经办人信息成功",
                    Data = handlerInfoList
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<List<HandlerInfo>>
                {
                    Code = ApiResultEnum.查询失败,
                    Message = $"查询经办人信息异常：{ex.Message}",
                    Data = null
                };
            }
        }
    }
}

